package com.zhilianbao.leyaogo.ui.fragment.goodscategory;

import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bql.convenientlog.CLog;
import com.bql.utils.EventManager;
import com.bql.variousbanner.widget.loopviewpager.ViewPagerCompat;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.events.LeEventCode;
import com.zhilianbao.leyaogo.http.api.CategoryApi;
import com.zhilianbao.leyaogo.http.callback.JsonCallback;
import com.zhilianbao.leyaogo.model.response.category.GoodsDetails;
import com.zhilianbao.leyaogo.model.response.category.SkuEntity;
import com.zhilianbao.leyaogo.model.response.shoppingcart.GoodsStock;
import com.zhilianbao.leyaogo.ui.fragment.base.BaseOkHttpFragment;
import com.zhilianbao.leyaogo.utils.GoodsSpecPopUtils;
import com.zhilianbao.leyaogo.utils.LogicCodeBlock;
import com.zhilianbao.leyaogo.utils.Utils;
import com.zhilianbao.leyaogo.utils.XToastUtils;
import com.zhilianbao.leyaogo.view.video.JCVideoPlayer;
import com.zhilianbao.leyaogo.view.widgets.DetailsTopBanner;
import com.zhilianbao.leyaogo.view.widgets.GoodsSignLayout;
import com.zhilianbao.leyaogo.view.widgets.MoneyTextView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 商品信息页面上半部分的fragment
 * Created by gyt on 2016/11/2
 */
public class GoodsInfoTopFragment extends BaseOkHttpFragment implements ViewPagerCompat.OnPageChangeListener {

    private static final String BUNDLE_GOODS_DETAILS = "bundle_goods_details";
    @BindView(R.id.goods_details_top_banner)
    DetailsTopBanner mGoodsDetailsTopBanner;
    @BindView(R.id.tv_details_goods_name)
    TextView         mTvDetailsGoodsName;
    @BindView(R.id.tv_details_goods_desc)
    TextView         mTvDetailsGoodsDesc;
    @BindView(R.id.tv_indicator)
    TextView         mTvIndicator;
    @BindView(R.id.tv_details_goods_price_vip)
    MoneyTextView    mTvDetailsGoodsPriceVip;
    @BindView(R.id.tv_details_goods_price_normal)
    MoneyTextView    mTvDetailsGoodsPriceNormal;
    @BindView(R.id.tv_spec_desc)
    TextView         mTvSpecDesc;
    @BindView(R.id.iv_spec_more)
    ImageView        mIvSpecMore;
    @BindView(R.id.rl_container_spec)
    RelativeLayout   mRlContainerSpec;
    @BindView(R.id.view_divider_spec_bottom)
    View             mViewDividerSpec;
    @BindView(R.id.gsl_goods_sign)
    GoodsSignLayout  mGslGoodsSign;
    @BindView(R.id.view_divider_sign_bottom)
    View             mViewDividerSign;


    private GoodsDetails mGoodsDetails;

    public static GoodsInfoTopFragment getInstance(GoodsDetails details) {

        GoodsInfoTopFragment fragment = new GoodsInfoTopFragment();
        Bundle bundle = new Bundle();
        bundle.putParcelable(BUNDLE_GOODS_DETAILS, details);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_goods_info_content;
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {

        if (getArguments() == null) {
            return;
        }
        mGoodsDetails = getArguments().getParcelable(BUNDLE_GOODS_DETAILS);

        String goodsName = mGoodsDetails.getGoodsName();
        int goodsSkuId = mGoodsDetails.getGoodsSkuId();
        int goodsType = mGoodsDetails.getGoodsType();
        List<SkuEntity> skuEntities = mGoodsDetails.getSku();
        mTvDetailsGoodsName.setText(goodsName);
        mTvDetailsGoodsDesc.setText(mGoodsDetails.getGoodsDesc());

        // 如果商品是SKU商品，才显示规格布局
        mRlContainerSpec.setVisibility(mGoodsDetails.getGoodsType() == 1 ? View.VISIBLE : View.GONE);
        mViewDividerSpec.setVisibility(mGoodsDetails.getGoodsType() == 1 ? View.VISIBLE : View.GONE);

        // 如果轮播图没有数据则显示商品图片
        List<String> goodsPics = Utils.getGoodsFiles(mGoodsDetails, 0);
        if (goodsPics == null || goodsPics.size() == 0) {
            goodsPics = new ArrayList<>();
            goodsPics.add(mGoodsDetails.getGoodsPic());
        }

        mGoodsDetailsTopBanner.setSource(goodsPics).startScroll();
        mGoodsDetailsTopBanner.addOnPageChangeListener(this);


        String goodsSign = mGoodsDetails.getGoodsSign();
        if (!TextUtils.isEmpty(goodsSign)) {
            String[] goodsSigns = goodsSign.split(",");
            List<String> goodsSignLists = Arrays.asList(goodsSigns);
            mGslGoodsSign.setSignData(goodsSignLists);
            mViewDividerSign.setVisibility(View.VISIBLE);
        } else {
            mGslGoodsSign.setVisibility(View.GONE);
            mViewDividerSign.setVisibility(View.GONE);
        }
        // 如果是sku商品并且有默认规格skuId，则商品价格根据skuId来获得，否则直接那price字段来获得
        if (goodsType == 1 && goodsSkuId != 0) {
            for (SkuEntity skuEntity : skuEntities) {
                if (skuEntity.getGoodsSkuId() == goodsSkuId) {
                    setGoodsSpecDesc(skuEntity);
                    mTvDetailsGoodsPriceVip.setAmount(skuEntity.getPrice());
                    mTvDetailsGoodsPriceNormal.setAmount(skuEntity.getMPrice());
                    break;
                }
            }
        } else {
            mTvDetailsGoodsPriceVip.setAmount(mGoodsDetails.getPrice());
            mTvDetailsGoodsPriceNormal.setAmount(mGoodsDetails.getMPrice());
            mTvSpecDesc.setText(mActivity.getResources().getString(R.string.msg_please_select_));
        }
    }

    /**
     * 设置商品规格描述控件内容
     *
     * @param skuEntity
     */
    public void setGoodsSpecDesc(SkuEntity skuEntity) {
        String goodsItemVals = skuEntity.getItemVals();
        String comments = skuEntity.getComments();
        if (TextUtils.isEmpty(comments)) {
            mTvSpecDesc.setText(goodsItemVals);
        } else {
            mTvSpecDesc.setText("[ " + comments + " ] " + goodsItemVals);
        }
    }

    @OnClick(R.id.rl_container_spec)
    public void onClick(View view) {
        showSpecPop();
    }

    private void showSpecPop() {
        Utils.showSpecPop(mActivity, getView(), /*mGoodsDetailsTopBanner.getDrawable(0)*/ mGoodsDetails.getStatusCode(), mGoodsDetails.getGoodsPic(), mGoodsDetails.getGoodsSkuId(), mGoodsDetails.getSelectedSkuId(), mGoodsDetails.getSku(), mGoodsDetails.getSkuMap(), new GoodsSpecPopUtils.OnPopClickListener() {
            @Override
            public void onAddToCart(View v, int goodsSkuId) {
                mGoodsDetails.setGoodsSkuId(goodsSkuId);
                if (Utils.isUserLogin(true, LogicCodeBlock.LogicState.AddToCart.value)) {
                    addToCart(mGoodsDetails);
                } else {
                    XToastUtils.showShortToast(R.string.msg_login_to_add_goods);
                    LogicCodeBlock.create().registerLogicCodeCallback(new LogicCodeBlock.LogicCodeBlockCallback() {
                        @Override
                        public void next(int logicState) {
                            if (logicState == LogicCodeBlock.LogicState.AddToCart.value) {
                                addToCart(mGoodsDetails);
                            }
                        }
                    });
                }

            }

            @Override
            public void onSpecSelect(SkuEntity skuEntity) {
                // 把用户选中的规格SkuId设置到javaBean中，确保再次点击后显示之前选中的规格
                CLog.i("=====================skuId = " + skuEntity.getGoodsSkuId());
                mGoodsDetails.setSelectedSkuId(skuEntity.getGoodsSkuId());
                mTvDetailsGoodsPriceNormal.setAmount(skuEntity.getMPrice());
                mTvDetailsGoodsPriceVip.setAmount(skuEntity.getPrice());
                setGoodsSpecDesc(skuEntity);

                EventBus.getDefault().post(new EventManager<Integer>(LeEventCode.MSG_CODE_GOODS_SKU_ID, skuEntity.getGoodsSkuId()));
            }
        });
    }

    /**
     * 把商品添加到购物车
     */
    private void addToCart(GoodsDetails goodsDetails) {
        int userId = (int) Utils.getUserLoginInfo().getUserId();
        int goodsId = goodsDetails.getGoodsId();
        int supplierId = goodsDetails.getSupplierId();
        int shopId = goodsDetails.getShopId();
        int goodsSkuId = goodsDetails.getGoodsSkuId();

        CategoryApi.addToShoppingCart(mActivity, userId, goodsId, supplierId, shopId, goodsSkuId, 1, 0, new JsonCallback<GoodsStock>(mActivity) {

            @Override
            public void onSuccess(GoodsStock goodsStock, Call call, Response response) {
                // 刷新购物车商品num
                EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_ADD_TO_SHOPPING_CART));
                XToastUtils.showShortToast(R.string.msg_add_to_shoppingCart_sucs);
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
            }
        });
    }

    @Override
    public boolean registerEventBus() {
        return true;
    }

    @Override
    protected void onHandleEvent(EventManager eventManager) {
        super.onHandleEvent(eventManager);
        if (eventManager.getEventCode() == LeEventCode.MSG_CODE_SHOW_SPEC_POP) {
            showSpecPop();
        }
    }

    //
    //    /**
    //     * 动态设置商品规格布局居中
    //     */
    //    private void setGoodsSpecCenter() {
    //        DisplayMetrics dm = new DisplayMetrics();
    //        mActivity.getWindowManager().getDefaultDisplay().getMetrics(dm);
    //        final int screenWidth = dm.widthPixels;
    //
    //        mLlContainer.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    //            @Override
    //            public void onGlobalLayout() {
    //                GoodsSpecLayout childAt = (GoodsSpecLayout) mLlContainer.getChildAt(1);
    //                TextView textView = (TextView) mLlContainer.getChildAt(0);
    //                int measuredWidth2 = textView.getMeasuredWidth();
    //                int measuredWidth1 = childAt.getChildAt(0).getMeasuredWidth();
    //
    //                int offset = screenWidth / 2 - (measuredWidth2 + measuredWidth1 / 2);
    //                RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    //                lp.setMargins(offset, 0, 0, 0);
    //                mLlContainer.setLayoutParams(lp);
    //                mLlContainer.getViewTreeObserver().removeOnGlobalLayoutListener(this);
    //            }
    //        });
    //
    //    }


    public void setOpenIndicator(boolean close) {
        if (close) {
            mTvIndicator.setText("上拉查看商品详情");
            Drawable drawable = getResources().getDrawable(R.drawable.ic_up_pull);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            mTvIndicator.setCompoundDrawables(drawable, null, null, null);
        } else {
            mTvIndicator.setText("下拉查看商品信息");
            Drawable drawable = getResources().getDrawable(R.drawable.ic_down_pull);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            mTvIndicator.setCompoundDrawables(drawable, null, null, null);
        }
    }

    @Override
    protected void initToolbarHere() {

    }

    @Override
    public void onPause() {
        super.onPause();
        JCVideoPlayer.releaseAllVideos();
    }

    @Override
    public boolean onBackPressedSupport() {
        if (JCVideoPlayer.backPress()) {
            return true;
        }
        return super.onBackPressedSupport();
    }

    @Override
    public void onPageScrolled(int i, float v, int i1) {

    }

    @Override
    public void onPageSelected(int i) {
        CLog.i("onPageSelected" + i);
        JCVideoPlayer.releaseAllVideos();
        mGoodsDetailsTopBanner.getIndicatorContainer().setVisibility(View.VISIBLE);
    }

    @Override
    public void onPageScrollStateChanged(int i) {

    }
}
